<template>
  <div class="card">
    <h2>注册账号</h2>
    <form @submit.prevent="submit">
      <input v-model="username" placeholder="3-12位字母数字" :class="{ invalid: username && !validUser }" />
      <input v-model="password" type="password" placeholder="6-16位密码" :class="{ invalid: password && !validPwd }" />
      <input v-model="password2" type="password" placeholder="确认密码" :class="{ invalid: password2 && !validPwd2 }" />


      <div v-if="username && !validUser" class="msg">用户名格式错误</div>
      <div v-if="password && !validPwd" class="msg">密码长度 6-16 位</div>
      <div v-if="password2 && !validPwd2" class="msg">两次密码不一致</div>

      <button type="submit" :disabled="!ok">立即注册</button>
    </form>

    <p v-if="err" class="err">{{ err }}</p>

    <p v-if="succ" class="succ">注册成功！{{ countdown }} 秒后跳转...</p>
    <router-link to="/login">已有账号？去登录</router-link>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

const username = ref('')
const password = ref('')
const password2 = ref('')
const err   = ref('')
const succ  = ref(false)
const router = useRouter()

const countdown = ref(0)
let timer: number | null = null

const validUser  = computed(() => /^[a-zA-Z0-9]{3,12}$/.test(username.value))
const validPwd   = computed(() => password.value.length >= 6 && password.value.length <= 16)
const validPwd2  = computed(() => password.value === password2.value && password2.value !== '')
const ok = computed(() => validUser.value && validPwd.value && validPwd2.value)

function submit() {
  const users: Record<string, string> = JSON.parse(localStorage.getItem('users') || '{}')
  if (users[username.value]) { err.value = '用户名已存在'; return }

  users[username.value] = password.value
  localStorage.setItem('users', JSON.stringify(users))

  succ.value = true
  countdown.value = 2
  timer = window.setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer!)
      timer = null
      router.push('/login')
    }
  }, 1000)
}
</script>

<style scoped src="@/assets/RegisterView.css"></style>